home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
cpp_libs
/
answrbok
/
6_4.lha
/
6_4
/
6_4.h
next >
Wrap
C/C++ Source or Header
|
1993-08-08
|
2KB
|
115 lines
* Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
* The C++ Answer Book */
* Tony Hansen */
* All rights reserved. */
/ Exercise 6.4
/ String class with value semantics
/ and copying on assignment.
ifndef STR_H
define STR_H
include <stream.h>
include <string.h>
/ a helper typedef for the cast
/ back into a character pointer
ypedef const char *charptr;
lass string
char *p;
int size;
ublic:
// string s;
string()
{
p = new char[size = 1];
p[0] = 0;
}
// string s(5);
string(int sz)
{
if (sz <= 0) sz = 1;
p = new char[size = sz];
p[0] = 0;
}
// string s("xyz");
string(char *s)
{
p = new char[size = strlen(s) + 1];
strcpy(p, s);
}
// string s = string
string &operator=(string &s)
{
delete p;
p = new char[size = s.size];
strcpy(p, s.p);
return *this;
}
// string s = "xyz";
string &operator=(char *s)
{
delete p;
p = new char[size = strlen(s) + 1];
strcpy(p, s);
return *this;
}
~string()
{ delete p; }
// const char *c = s;
charptr operator charptr()
{ return (charptr)p; }
// x = s[3];
// s[3] = 'x';
char &operator[](int i)
{
if (i < 0 || i >= size)
return p[0];
else
return p[i];
}
friend ostream& operator<<(ostream&, string&);
friend istream& operator>>(istream&, string&);
friend int operator==(string &x, char *s)
{ return strcmp(x.p, s) == 0; }
friend int operator==(string &x, string &y)
{ return strcmp(x.p, y.p) == 0; }
friend int operator!=(string &x, char *s)
{ return strcmp(x.p, s) != 0; }
friend int operator!=(string &x, string &y)
{ return strcmp(x.p, y.p) != 0; }
// DELETE
void outputstring() // DELETE
{ // DELETE
cout << "\tsize = " << size << "\n"; // DELETE
cout << "\tp = '" << p << "'\n"; // DELETE
} // DELETE
;
nline ostream& operator<<(ostream &s, string &x)
return s << x.p;
nline istream& operator>>(istream &s, string &x)
char buf[1024];
s >> buf;
x = buf;
return s;
endif /* STR_H */